<script lang="ts" setup>
import { ref, onMounted, h } from 'vue';
import {
  Card,
  Descriptions,
  Table,
  Button,
  Tag,
  Space,
  Input,
  Select,
  Modal,
  message,
  Row,
  Col
} from 'ant-design-vue';
import type { TableColumnsType } from 'ant-design-vue';
import { useRouter, useRoute } from 'vue-router';
import {
  exportTaskMemberListApi,
  exportTaskSettlementTemplateApi,
  getTaskApplicationsApi,
  approveTaskApplicationApi,
  rejectTaskApplicationApi,
  dimissionTaskApplicationApi,
} from '#/api/core/task-application';

/**
 * 任务基本信息接口
 */
interface TaskInfo {
  id: string;
  name: string;
  service_type: string;
  status: 'inactive' | 'active';
  start_time: string;
  end_time: string;
  min_fee: number;
  max_fee: number;
  work_location: string;
  age_requirement: string;
  gender_requirement: string;
  education_requirement: string;
  experience_requirement: string;
}

/**
 * 候选者记录接口
 */
interface CandidateRecord {
  id: string;
  name: string;
  phone: string;
  id_number: string;
  status: string;
  status_label: string;
  bank_card: string;
  sign_status?: string;
  contact_status?: string;
  created_at?: string;
}

/**
 * 分页参数接口
 */
interface PaginationParams {
  current: number;
  pageSize: number;
  total: number;
}

const router = useRouter();
const route = useRoute();
const taskId = route.params.id as string;

const loading = ref(false);
const candidateLoading = ref(false);
const searchText = ref(''); // 姓名搜索
const phoneSearchText = ref(''); // 手机号搜索
const statusFilter = ref<string>(''); // 状态筛选
const batchExportLoading = ref(false);
const settlementExportLoading = ref(false);

// 任务信息
const taskInfo = ref<TaskInfo>({
  id: '',
  name: '',
  service_type: '',
  status: 'inactive',
  start_time: '',
  end_time: '',
  min_fee: 0,
  max_fee: 0,
  work_location: '',
  age_requirement: '',
  gender_requirement: '',
  education_requirement: '',
  experience_requirement: '',
});

// 候选者数据
const candidateData = ref<CandidateRecord[]>([]);
const pagination = ref<PaginationParams>({
  current: 1,
  pageSize: 10,
  total: 0,
});

const sortField = ref<'name' | 'phone' | 'status' | 'created_at'>('name');
const sortOrder = ref<'asc' | 'desc'>('asc');

// 审核模态框相关
const reviewModalVisible = ref(false);
const currentReviewCandidate = ref<CandidateRecord | null>(null);

// 状态选项
const statusOptions = [
  { label: '全部', value: '' },
  { label: '待处理', value: 'pending' },
  { label: '已录用', value: 'approved' },
  { label: '已拒绝', value: 'rejected' },
  { label: '已完成', value: 'completed' },
  { label: '已取消', value: 'cancelled' },
  { label: '已离岗', value: 'dimission' },
];

// 联系状态选项
const contactStatusOptions = [
  { label: '全部', value: '' },
  { label: '满意度调研', value: 'survey' },
  { label: '常规咨询', value: 'consultation' },
  { label: '其他', value: 'other' },
];

/**
 * 状态标签颜色映射
 */
const getStatusColor = (status: string) => {
  const colorMap: Record<string, string> = {
    'pending': 'default',
    'approved': 'success',
    'rejected': 'error',
    'completed': 'success',
    'cancelled': 'warning',
    'dimission': 'warning',
  };
  return colorMap[status] || 'default';
};

/**
 * 状态文本映射
 */
const getStatusText = (status: string) => {
  const textMap: Record<string, string> = {
    'pending': '待处理',
    'approved': '已录用',
    'rejected': '已拒绝',
    'completed': '已完成',
    'cancelled': '已取消',
    'dimission': '已离岗',
  };
  return textMap[status] || status;
};

/**
 * 表格列定义
 */
const columns: TableColumnsType<CandidateRecord> = [
  {
    title: '姓名',
    dataIndex: 'name',
    key: 'name',
    width: 100,
    sorter: true,
    defaultSortOrder: 'ascend',
  },
  {
    title: '手机号',
    dataIndex: 'phone',
    key: 'phone',
    width: 130,
    sorter: true,
  },
  {
    title: '身份证号',
    dataIndex: 'id_number',
    key: 'id_number',
    width: 180,
    customRender: ({ text }) => {
      // 身份证号脱敏处理
      return text ? text.replace(/(\d{6})\d{8}(\d{4})/, '$1********$2') : '';
    }
  },
  {
    title: '报名状态',
    dataIndex: 'status',
    key: 'status',
    width: 100,
    sorter: true,
    customRender: ({ record }) => h(Tag, { color: getStatusColor(record.status) }, () => record.status_label),
  },
  {
    title: '银行卡',
    dataIndex: 'bank_card',
    key: 'bank_card',
    width: 180,
    customRender: ({ text }) => {
      // 银行卡号脱敏处理
      return text ? text.replace(/(\d{4})\d{8,12}(\d{4})/, '$1****$2') : '';
    }
  },
  {
    title: '联系状态',
    dataIndex: 'contact_status',
    key: 'contact_status',
    width: 120,
    customRender: ({ text }) => {
      const statusMap: Record<string, string> = {
        'survey': '满意度调研',
        'consultation': '常规咨询',
        'other': '其他',
      };
      return statusMap[text] || text;
    }
  },
  {
    title: '报名时间',
    dataIndex: 'created_at',
    key: 'created_at',
    width: 160,
    sorter: true,
  },
  {
    title: '操作',
    key: 'action',
    width: 300,
    fixed: 'right',
    customRender: ({ record }) => {
      return h(Space, {}, () => [
        h(Button, {
          type: 'primary',
          size: 'small',
          disabled: record.status !== 'pending',
          onClick: () => handleReview(record)
        }, () => '审核'),
        h(Button, {
          type: 'link',
          size: 'small',
          onClick: () => handleViewDetail(record.id)
        }, () => '查看'),
        h(Button, {
          type: 'link',
          size: 'small',
          danger: true,
          disabled: !['approved', 'completed'].includes(record.status) || record.status === 'dimission',
          onClick: () => handleResign(record.id)
        }, () => '离岗'),
      ]);
    },
  },
];

/**
 * 获取任务详情
 */
const fetchTaskDetail = async () => {
  loading.value = true;
  try {
    // TODO: 调用实际API
    // const response = await getTaskDetailApi(taskId);

    // 模拟数据
    taskInfo.value = {
      id: taskId,
      name: 'PPT制作',
      service_type: '制作类',
      status: 'active',
      start_time: '2025-06-17',
      end_time: '2026-06-16',
      min_fee: 10000,
      max_fee: 80000,
      work_location: '全国',
      age_requirement: '18岁-65岁',
      gender_requirement: '不限',
      education_requirement: '不限',
      experience_requirement: '不限',
    };
  } catch (error) {
    console.error('获取任务详情失败:', error);
    message.error('获取任务详情失败，请稍后重试');
  } finally {
    loading.value = false;
  }
};

/**
 * 获取候选者数据
 */
const fetchCandidateData = async () => {
  candidateLoading.value = true;
  try {
    const response = await getTaskApplicationsApi(taskId, {
    page: pagination.value.current,
    per_page: pagination.value.pageSize,
    name: searchText.value || undefined,
    phone: phoneSearchText.value || undefined,
    status: statusFilter.value || undefined,
    sort_by: sortField.value,
    sort_order: sortOrder.value,
  });

    const { data, current_page, per_page, total } = response.applications;

    candidateData.value = data.map((item) => ({
      ...item,
      id_number: item.id_number || '',
      bank_card: item.bank_card || '',
      status_label: item.status_label || getStatusText(item.status),
      contact_status: item.contact_status || '',
      created_at: item.created_at || '',
    }));

    pagination.value.total = total;
    pagination.value.current = current_page;
    pagination.value.pageSize = per_page;
  } catch (error) {
    console.error('获取候选者数据失败:', error);
    message.error('获取候选者数据失败，请稍后重试');
  } finally {
    candidateLoading.value = false;
  }
};

/**
 * 打开审核模态框
 */
const handleReview = (candidate: CandidateRecord) => {
  currentReviewCandidate.value = candidate;
  reviewModalVisible.value = true;
};

/**
 * 关闭审核模态框
 */
const handleCloseReviewModal = () => {
  reviewModalVisible.value = false;
  currentReviewCandidate.value = null;
};

/**
 * 审核通过
 */
const handleApproveCandidate = async () => {
  if (!currentReviewCandidate.value) return;

  try {
    await approveTaskApplicationApi(taskId, currentReviewCandidate.value.id);

    message.success('审核通过');
    handleCloseReviewModal();
    await fetchCandidateData();
  } catch (error) {
    console.error('审核失败:', error);
    message.error('审核失败，请稍后重试');
  }
};

/**
 * 审核不通过
 */
const handleRejectCandidate = async () => {
  if (!currentReviewCandidate.value) return;

  try {
    await rejectTaskApplicationApi(taskId, currentReviewCandidate.value.id, {
      reason: '审核未通过',
    });

    message.success('审核不通过');
    handleCloseReviewModal();
    await fetchCandidateData();
  } catch (error) {
    console.error('审核失败:', error);
    message.error('审核失败，请稍后重试');
  }
};

/**
 * 查看候选者详情
 */
const handleViewDetail = (candidateId: string) => {
  // TODO: 跳转到候选者详情页面或打开详情弹窗
  console.log('查看候选者详情:', candidateId);
  message.info('查看候选者详情功能开发中');
};

/**
 * 候选者离岗
 */
const handleResign = async (candidateId: string) => {
  Modal.confirm({
    title: '确认离岗',
    content: '确定要将这位候选者设置为离岗状态吗？',
    onOk: async () => {
      try {
        await dimissionTaskApplicationApi(taskId, candidateId);

        message.success('离岗设置成功');
        await fetchCandidateData();
      } catch (error) {
        console.error('离岗设置失败:', error);
        message.error('离岗设置失败，请稍后重试');
      }
    },
  });
};

/**
 * 搜索处理
 */
const handleSearch = () => {
  pagination.value.current = 1;
  fetchCandidateData();
};

/**
 * 重置搜索
 */
const handleReset = () => {
  searchText.value = '';
  phoneSearchText.value = '';
  statusFilter.value = '';
  pagination.value.current = 1;
  fetchCandidateData();
};

/**
 * 分页变化处理
 */
const handleTableChange = (pag: any, _filters: any, sorter: any) => {
  pagination.value.current = pag.current;
  pagination.value.pageSize = pag.pageSize;

  const field = sorter?.field as string | undefined;
  if (field && ['name', 'phone', 'status', 'created_at'].includes(field)) {
    sortField.value = field as typeof sortField.value;
  } else if (!sorter?.order) {
    sortField.value = 'name';
  }

  if (sorter?.order) {
    sortOrder.value = sorter.order === 'descend' ? 'desc' : 'asc';
  } else if (!sorter?.order) {
    sortOrder.value = 'asc';
  }

  fetchCandidateData();
};

/**
 * 返回任务列表
 */
const handleGoBack = () => {
  router.push({ name: 'TaskCenter' });
};

const buildExportFilters = () => ({
  name: searchText.value || undefined,
  phone: phoneSearchText.value || undefined,
  status: statusFilter.value || undefined,
});

const downloadBlobFile = (blob: Blob, filename: string) => {
  const link = document.createElement('a');
  const url = window.URL.createObjectURL(blob);
  link.href = url;
  link.download = filename;
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
  window.URL.revokeObjectURL(url);
};

const handleBatchExport = async () => {
  batchExportLoading.value = true;
  try {
    const { blob, filename } = await exportTaskMemberListApi(
      taskId,
      buildExportFilters(),
    );
    downloadBlobFile(blob, filename);
    message.success('成员列表导出成功');
  } catch (error) {
    console.error('批量导出失败:', error);
    message.error('成员列表导出失败，请稍后重试');
  } finally {
    batchExportLoading.value = false;
  }
};

const handleExportSettlement = async () => {
  settlementExportLoading.value = true;
  try {
    const { blob, filename } = await exportTaskSettlementTemplateApi(
      taskId,
      buildExportFilters(),
    );
    downloadBlobFile(blob, filename);
    message.success('结算模板导出成功');
  } catch (error) {
    console.error('结算单导出失败:', error);
    message.error('结算模板导出失败，请稍后重试');
  } finally {
    settlementExportLoading.value = false;
  }
};

/**
 * 页面初始化
 */
onMounted(() => {
  fetchTaskDetail();
  fetchCandidateData();
});
</script>

<template>
  <div class="task-detail-container">
    <!-- 页面标题和返回按钮 -->
    <div class="page-header">
      <Button @click="handleGoBack" style="margin-bottom: 16px;">
        ← 返回任务列表
      </Button>
    </div>

    <!-- 任务基本信息 -->
    <Card title="基本信息" :loading="loading" style="margin-bottom: 16px;">
      <Descriptions :column="3">
        <Descriptions.Item label="任务ID">
          {{ taskInfo.id }}
        </Descriptions.Item>
        <Descriptions.Item label="任务名称">
          {{ taskInfo.name }}
        </Descriptions.Item>
        <Descriptions.Item label="服务类型">
          {{ taskInfo.service_type }}
        </Descriptions.Item>
        <Descriptions.Item label="任务周期">
          {{ taskInfo.start_time }} 至 {{ taskInfo.end_time }}
        </Descriptions.Item>
        <Descriptions.Item label="结算周期">
          月结
        </Descriptions.Item>
        <Descriptions.Item label="任务计费">
          {{ taskInfo.min_fee.toLocaleString() }} - {{ taskInfo.max_fee.toLocaleString() }}元/次
        </Descriptions.Item>
        <Descriptions.Item label="学历要求">
          {{ taskInfo.education_requirement }}
        </Descriptions.Item>
        <Descriptions.Item label="年龄要求">
          {{ taskInfo.age_requirement }}
        </Descriptions.Item>
        <Descriptions.Item label="经验要求">
          {{ taskInfo.experience_requirement }}
        </Descriptions.Item>
        <Descriptions.Item label="工作地点">
          {{ taskInfo.work_location }}
        </Descriptions.Item>
        <Descriptions.Item label="任务描述">
          <a href="#" style="color: #1890ff;">查看详情</a>
        </Descriptions.Item>
      </Descriptions>
    </Card>

    <!-- 候选者管理 -->
    <Card title="候选者管理">
      <!-- 搜索栏 -->
      <div class="search-bar" style="margin-bottom: 16px;">
        <Space wrap>
          <Input
            v-model:value="searchText"
            placeholder="请输入姓名"
            style="width: 200px;"
          />
          <Input
            v-model:value="phoneSearchText"
            placeholder="请输入手机号"
            style="width: 200px;"
          />
          <Select
            v-model:value="statusFilter"
            placeholder="请选择报名状态"
            style="width: 200px;"
            :options="statusOptions"
          />
          <Button type="primary" @click="handleSearch">
            查询
          </Button>
          <Button @click="handleReset">
            重置
          </Button>
          <Button type="link" :loading="batchExportLoading" @click="handleBatchExport">
            批量导出
          </Button>
          <Button
            type="link"
            :loading="settlementExportLoading"
            @click="handleExportSettlement"
          >
            导出结算单
          </Button>
        </Space>
      </div>

      <!-- 候选者表格 -->
      <Table
        :columns="columns"
        :data-source="candidateData"
        :loading="candidateLoading"
        :pagination="{
          current: pagination.current,
          pageSize: pagination.pageSize,
          total: pagination.total,
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total: number, range: number[]) => `共 ${total} 条`,
        }"
        :scroll="{ x: 1200 }"
        @change="handleTableChange"
      />
    </Card>

    <!-- 审核模态框 -->
    <Modal
      v-model:open="reviewModalVisible"
      title="候选者审核"
      width="600px"
      :footer="false"
      @cancel="handleCloseReviewModal"
    >
      <div v-if="currentReviewCandidate" class="space-y-4">
        <!-- 基本信息 -->
        <div class="border rounded-lg p-4">
          <h4 class="text-lg font-medium mb-3">基本信息</h4>
          <Row :gutter="[16, 8]">
            <Col :span="12">
              <div class="text-sm">
                <span class="text-gray-600">姓名：</span>
                <span class="text-gray-900">{{ currentReviewCandidate.name }}</span>
              </div>
            </Col>
            <Col :span="12">
              <div class="text-sm">
                <span class="text-gray-600">手机号：</span>
                <span class="text-gray-900">{{ currentReviewCandidate.phone }}</span>
              </div>
            </Col>
            <Col :span="12">
              <div class="text-sm">
                <span class="text-gray-600">身份证号：</span>
                <span class="text-gray-900">{{ currentReviewCandidate.id_number }}</span>
              </div>
            </Col>
            <Col :span="12">
              <div class="text-sm">
                <span class="text-gray-600">银行卡号：</span>
                <span class="text-gray-900">{{ currentReviewCandidate.bank_card }}</span>
              </div>
            </Col>
            <Col :span="12">
              <div class="text-sm">
                <span class="text-gray-600">报名时间：</span>
                <span class="text-gray-900">{{ currentReviewCandidate.created_at }}</span>
              </div>
            </Col>
            <Col :span="12">
              <div class="text-sm">
                <span class="text-gray-600">当前状态：</span>
                <Tag :color="getStatusColor(currentReviewCandidate.status)">
                  {{ getStatusText(currentReviewCandidate.status) }}
                </Tag>
              </div>
            </Col>
          </Row>
        </div>

        <!-- 身份证照片（模拟） -->
        <div class="border rounded-lg p-4">
          <h4 class="text-lg font-medium mb-3">身份证照片</h4>
          <Row :gutter="16">
            <Col :span="12">
              <div class="text-center">
                <div class="border-2 border-dashed border-gray-300 rounded-lg p-8 mb-2">
                  <div class="text-gray-400">身份证正面</div>
                </div>
              </div>
            </Col>
            <Col :span="12">
              <div class="text-center">
                <div class="border-2 border-dashed border-gray-300 rounded-lg p-8 mb-2">
                  <div class="text-gray-400">身份证反面</div>
                </div>
              </div>
            </Col>
          </Row>
        </div>

        <!-- 操作按钮 -->
        <div class="flex justify-end space-x-3 pt-4 border-t">
          <Button @click="handleCloseReviewModal">
            关闭
          </Button>
          <Button
            type="default"
            @click="handleRejectCandidate"
            :disabled="currentReviewCandidate.status !== 'pending'"
          >
            未通过
          </Button>
          <Button
            type="primary"
            @click="handleApproveCandidate"
            :disabled="currentReviewCandidate.status !== 'pending'"
          >
            通过
          </Button>
        </div>
      </div>
    </Modal>
  </div>
</template>

<style scoped>
.task-detail-container {
  padding: 24px;
}

.page-header {
  margin-bottom: 16px;
}

.search-bar {
  padding: 16px;
  background: #fafafa;
  border-radius: 6px;
}
</style>
